/***************************************************************************
 *   Copyright (C) 2007 by saa   *
 *   root@saa   *
 ***************************************************************************/

#include <QHostAddress>

#include "database.h"

//db creation script
#if 0
   QString query("create table routeserver (hostname,"
                                            "password,"
                                            "username,"
                                            "login_pattern,"
                                            "password_pattern,"
                                            "prompt);");
    db.exec(query);
    QSqlQuery sqlQuery;
    QString queryString("SELECT hostname, password, username, login_pattern, password_pattern, prompt FROM routeserver1 WHERE system_type != 'junos' AND system_type != 'zebra' AND hostname != 'tpr-route-server.saix.net' AND can_traceroute = 'true';");
    if(sqlQuery.exec(queryString)){
        while(sqlQuery.next()){
            QString query1 = QString("insert into routeserver values('%1', '%2', '%3', '%4', '%5', '%6')").
                    arg(sqlQuery.value(0).toString()).\
                    arg(sqlQuery.value(1).toString()).\
                    arg(sqlQuery.value(2).toString()).\
                    arg(sqlQuery.value(3).toString()).\
                    arg(sqlQuery.value(4).toString()).\
                    arg(sqlQuery.value(5).toString());
            qDebug() << query1;
            db.exec(query1);
            log(db.lastError().text());

        }
    } else
        log(sqlQuery.lastError().text());
#endif


void Database::getRouteServerList(const QString & fileName, QList<RouteServer> * routeServerList) const
{
    if(routeServerList){
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "get_routesever_list");
        db.setDatabaseName(fileName);
        if(db.open()){
            QSqlQuery query(db);
            QString queryString("SELECT hostname, password, username, login_pattern, password_pattern, prompt FROM routeserver;");
            if(query.exec(queryString)){
                while(query.next()){
                    routeServerList->append(RouteServer(query.value(0).toString(),
                                                        query.value(1).toString(),
                                                        query.value(2).toString(),
                                                        query.value(3).toString(),
                                                        query.value(4).toString(),
                                                        query.value(5).toString()));
                }
            } else
                log(query.lastError().text());
        } else
            db.close();
        return;
    }
    QSqlDatabase::removeDatabase("get_routeserver_list");
}

LinkList Database::getLinkList(const QString & fileName) const
{
    LinkList linkList;
    {
        QSqlDatabase dbData = QSqlDatabase::addDatabase("QSQLITE", "get_link_list");
        dbData.setDatabaseName(fileName);
        if(dbData.open()){
            QSqlQuery query(dbData);
            QString queryString("SELECT * FROM link_list;");
            if(query.exec(queryString)){
                while(query.next()){
                    linkList.append(Link(query.value(0).toInt(),\
                                         query.value(1).toInt(),\
                                         query.value(2).toDouble(),\
                                         query.value(3).toInt()));
                }
            } else
                log(query.lastError().text());
            dbData.close();
        } else
            log(dbData.lastError().text());
    }
    QSqlDatabase::removeDatabase ("get_link_list");
    return linkList;
}


void Database::saveLinks(const QString & file, const LinkList & linkList ) const
{     
    if(file.isEmpty() || !linkList.size())
        return;

#if 0
    {
        QSqlDatabase dbData = QSqlDatabase::addDatabase("QSQLITE", "save_link");
        dbData.setDatabaseName(file);
        if(dbData.open()){
            QSqlQuery query(dbData);
            query.exec("create table link_list (first, second, average_time, path_count);");
            for (int i = 0; i < linkList.size(); ++i){
                QString insertQuery(QString("insert into link_list values(%1, %2, %3, %4);")\
                                    .arg(linkList.at(i).begin)\
                                    .arg(linkList.at(i).end)\
                                    .arg(linkList.at(i).averageTime)\
                                    .arg(linkList.at(i).nodeCount));
                if(!query.exec(insertQuery))
                    log(query.lastError().text());
            }
        } else
            log(dbData.lastError().text());
    }
    QSqlDatabase::removeDatabase ("save_link");
#endif

    //graphviz test

    QFile dotFile(file);
    dotFile.open(QFile::WriteOnly | QIODevice::Text);
    QTextStream out(&dotFile);
    out << "digraph G{" << endl;
    for (int i = 0; i < linkList.size(); ++i){
        //output string example
        //"216.191.167.134"->"216.191.167.133"[ label = "0.533332 / 5" ];
        out << "\"" << QHostAddress(linkList.at(i).begin).toString() << "\"->"\
            << "\"" << QHostAddress(linkList.at(i).end).toString() << "\""\
            << "[ label = " << "\"" << linkList.at(i).averageTime\
            << " / " << linkList.at(i).nodeCount  << "\" ];" << endl;
    }
    out << "}";
    out.flush();
    dotFile.close();
}

void Database::log( const QString & message, const LogFlag::LogLevels logFlag) const
{
    emit logDatabaseMessage(message, logFlag);
}
